var regions, proInd, cityInd;
var provinces, citys, districts;

const getNameFromList = function(L) {
    var rtn = new Array();
    for (var i in L) {
        var item = L[i];
        rtn.push(item.name);
    }
    return rtn;
};

const getListFromName = function(L, name, type) {
    for (var i in L) {
        var item = L[i];
        if (item.name == name) {
            if (type == 'city')
                return item.city_list;
            return item.district_list;
        }
    }
};

const getCityDist = function(that) {
    var region, region_range, nowregion = regions;
    region = [that.address.province, that.address.city, that.address.district];

    provinces = getNameFromList(nowregion);
    if (provinces.indexOf(region[0]) == -1)
        region[0] = provinces[0];
    proInd = provinces.indexOf(region[0]);

    nowregion = getListFromName(nowregion, region[0], 'city');
    citys = getNameFromList(nowregion);
    if (citys.indexOf(region[1]) == -1)
        region[1] = citys[0];
    cityInd = citys.indexOf(region[1]);

    nowregion = getListFromName(nowregion, region[1], 'district');
    districts = getNameFromList(nowregion);
    if (districts.indexOf(region[2]) == -1)
        region[2] = districts[0];

    that.regionValue = [proInd, cityInd, districts.indexOf(region[2])];

    region_range = [provinces, citys, districts];

    that.region = region;
    that.region_range = region_range;
};

const changeRegion = function(that, detail) {
    var nowregion = regions;
    if (detail.column == 0) {
        proInd = detail.value;
        that.regionValue[0] = detail.value;
        nowregion = getListFromName(nowregion, provinces[proInd], 'city');
        citys = getNameFromList(nowregion);
        detail.column = 1;
        detail.value = 0;
    }
    else nowregion = getListFromName(nowregion, provinces[proInd], 'city');

    if (detail.column == 1) {
        cityInd = detail.value;
        that.regionValue[1] = detail.value;
        nowregion = getListFromName(nowregion, citys[cityInd], 'district');
        districts = getNameFromList(nowregion);
        detail.column = 2;
        detail.value = 0;
    }

    if (detail.column == 2) {
        that.regionValue[2] = detail.value;
    }
    that.region_range = [provinces, citys, districts];
};

const initRegion = function(that, _regions) {
    regions = _regions;
    getCityDist(that);
};

export default {
    initRegion,
    changeRegion
};
